<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Jobs\SaveContractPdfController;
use App\Http\Requests\ProductRequest;
use App\Models\BaseModel;
use App\Models\Helper\IdBuilder;
use App\Models\ImportModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

// 数据库

use App\Http\Controllers\Controller;

class TestController extends Controller
{
//////////////////////////////////////////////// 测试

////////////////////// 商品1
///
    /**
     * 控制器初始化
     * @param Request $request
     */
    protected $request;
    protected $idBuilder;
    public function __construct(Request $request){
        $this->request = $request;
        $this->idBuilder = new IdBuilder();
    }

    public function generateSignature($params, $privateKey) {  
        // 剔除sign参数  
        if (isset($params['sign'])) {  
            unset($params['sign']);  
        }  
          
        // 参数排序  
        ksort($params);  
      
        // 生成签名字符串  
        $signString = '';  
        foreach ($params as $key => $value) {  
            $signString .= $key . '=' . $value;  
        }  
        $signString .= $privateKey; // 在字符串最后加上私钥  
      
        // 使用md5生成签名  
        return md5($signString); // 转换为大写，有些系统可能需要大写MD5  
    }  
      
    public function curls($url, $post=false, $head=''){
		$curl = curl_init(); // 启动一个CURL会话
		curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
		
		// 优化curl 速度
		curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
		curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);//强制使用IPV4协议解析域名
		// 头部
		if(!empty($head)){
//			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //头部要送出'Expect: '
			curl_setopt($curl, CURLOPT_HTTPHEADER, $head); // 请求头部
		}
		
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
//		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
		if(!empty($post)){
			curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
			curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
		}
		curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
		$res = curl_exec($curl); // 执行操作
		
		if (curl_errno($curl)) {
			echo 'Errno'.curl_error($curl);//捕抓异常
		}
		curl_close($curl); // 关闭CURL会话
		return $res; // 返回数据，json格式
	}
    
    public function testxin()
    {


        $bizParam = [
            'page' => 1, // 页码  
            'pageSize' => 10, // 每页条数  
        ];
        // 请求参数  
        $requestParams = [  
            'appId' => 'openApi_TEST', // 千易应用ID  
            'serviceType' => 'QUERY_WAREHOUSE_LIST', // 请求接口名  
            'bizParam'=>json_encode($bizParam),
            'timestamp' => time() * 1000, // 时间戳，单位毫秒   
        ];  
        
        // 私钥（从官方获取）  
        $privateKey = 'openApi_TOKEN';  
        
        // 生成签名  
        $requestParams['sign'] = $this->generateSignature($requestParams, $privateKey);  
        
        // 转换为查询字符串（如果你的API需要GET请求）  
        // $queryString = http_build_query($requestParams);  
        
        // API端点  
        $apiEndpoint = 'https://gerp-test1.800best.com/api/v1/warehouse';  
        // $apiEndpoint = 'https://gerp-test1.800best.com';  

                
        // 初始化cURL会话  
        $ch = curl_init();  
        
        // var_dump($apiEndpoint . '?' . $queryString);
        // return;
        // 设置cURL选项  
        // $ch = curl_init($apiEndpoint . '?' . $queryString);  
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        curl_setopt($ch, CURLOPT_URL, $apiEndpoint);  
        curl_setopt($ch, CURLOPT_POST, true); // 启用POST请求  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestParams); // 设置POST参数  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将返回结果保存到变量中，而不是直接输出  
        
        // 执行请求并获取响应  
        $response = curl_exec($ch);  
        
        // 检查是否有错误发生  
        if (curl_errno($ch)) {  
            echo 'cURL错误：' . curl_error($ch);  
        } else {  
            // 处理响应  
            echo '响应：' . $response;  
            var_dump($requestParams);
        }  
        
        // 关闭cURL会话  
        curl_close($ch);  
        // // 发送请求  
        // // 这里使用cURL作为示例  
        // $data = $this->curls();
        // var_dump($data);
        // $ch = curl_init($apiEndpoint . '?' . $queryString);  
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        
        // // 执行请求并获取响应  
        // $response = curl_exec($ch);  
        
        // // 检查是否有错误发生  
        // if (curl_errno($ch)) {  
        //     echo 'Error:' . curl_error($ch);  
        // } else {  
        //     // 处理响应  
        //     echo $response;  
        // }  
        
        // // 关闭cURL资源，并且释放系统资源  
        // curl_close($ch);
    }
    /**
     * 测试测试测试
     * http://newzity.com/pc/test/tets
     * http://new.zity.cn/pc/test/tets
     */
    public function tets()
    {
        /*$rabbitmq = new \App\Libs\wrapper\Rabbitmq('exchange_2', 'queue_2', 'key_2');
        //消息内容
        $msg_data = array();
        $msg_data['time_zx'] = time();// 执行时间
        $msg_data['shop_id'] = 1;
        $msg_data['sale'] = 1;//是否上架：1.上架，2.不上架
        $msg_data['parent_sku'] = 'SBTJC00021';//父sku
        //// 发送消息
        $rabbitmq->send_message($msg_data);exit;
        */

        $rabbitmq = new \App\Libs\wrapper\Rabbitmq('exchange_1', 'queue_1', 'key_1');
//		$rabbitmq = new \App\Libs\wrapper\Rabbitmq('exchange_2', 'queue_2', 'key_2');
        $callback = array($this, 'receives');
        $rabbitmq->deal_mq($callback);
    }

    public function dingdingtest(){
        $dingding = new \App\Models\BaseModel();
        $res = $dingding->DingdingSend('测试通知-php',['17689324297','13600971426']);
        var_dump($res);
    }

    /*
     * 接收消息并进行处理的回调方法
     * */
    public function receives($msg)
    {
        $msg_data = json_decode($msg->body, true);
//		$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);exit;// ack 确认
//		var_dump($msg_data);exit;
        // make：授权类型:1.wish，2.vova，3.lazada
        if ($msg_data['platform_id'] == 2) {
            // wish
            $return = $this->product_get_wish($msg_data);
        } else if ($msg_data['platform_id'] == 3) {
            // lazada
            $return = $this->product_get_lazada($msg_data);
        } else if ($msg_data['platform_id'] == 4) {
            // vova
            $return = $this->product_get_vova($msg_data);
        }

        var_dump($return);
        exit;
//		var_dump($return);exit;
        if ($return == 1) {
            // 完成
            $aa = $msg_data;
            $aa['code'] = 'ok_1';
            $aa = json_encode($aa);
            var_dump($aa);

            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        } else if ($return == 2) {
            // 获取下一页

            $aa = $msg_data;
            $aa['code'] = 'ok_2';
            $aa = json_encode($aa);
            var_dump($aa);

            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);

            //// 发送消息
            $msg_data['page'] = $msg_data['page'] + 1;//页码
            ($this->rabbitmq)->send_message($msg_data);
        }
        var_dump($return);
        exit;
        if ($return == 1) {
            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        }
        var_dump($return);
        exit;
    }

    /**
     * 清空redis
     * http://newzity.com/pc/test/redis_del
     * http://new.zity.cn/pc/test/redis_del
     */
    public function redis_del()
    {
        $redis = new \Redis();
        $redis->connect("127.0.0.1", 6379);
        $num = $redis->keys('*');// n1或n1234^ 都有效
//		$redis->del($num);
        var_dump($num);
        exit;

        $msg_data = array(
            'mq_id' => 'mq_product_5_2021-02-08 00:00:006422483b63a7aa5f4e52bbd19eac39ce',
            "shop_id" => 19,
            "mark" => 2,
            "page" => 1,
            "limit" => 10,
            "time_start" => "2021-01-01 00:00:00",
            "time_end" => "2021-02-01 00:00:00"
        );

        $call_lazada = new \App\Libs\platformApi\Lazada();
        $return = $call_lazada->product_get($msg_data);
        var_dump($return);
        exit;
    }


    //去除shopee_cost表中product_sku字段的空白字符串
    public function string_sku()
    {

        $sql = "select * 
                        from  shopee_cost 
                        where product_sku like '\t%' or product_sku like '\n%' or product_sku like '\t\n%' or product_sku like '\n\t%'
                                or product_sku like '%\t' or product_sku like '%\n' or product_sku like '%\t\n' or product_sku like '%\n\t'";
        $list = Db::select($sql);

        foreach ($list as $k => $v) {
            $product_sku = trim($v->product_sku);
            $find = Db::table('shopee_cost')->where('product_sku', $product_sku)->first();

            if (isset($find->id)) {
                $del = Db::table('shopee_cost')->where('id', $find->id)->delete();
            }

            $res = Db::table('shopee_cost')->where('id', $v->id)->update(['product_sku' => $product_sku]);
        }


    }


    public function GetToken()
    {
        $res = db::table('users')->where('Id',387)->first();
        return $res->token;
    }

    //去除shopee_order_item表中variation_sku字段的空白字符串
    public function item_sku()
    {
        $sql = "select id,variation_sku
                        from  shopee_order_items
                        where variation_sku like '\t%' or variation_sku like '\n%' or variation_sku like '\t\n%' or variation_sku like '\n\t%'
                                or variation_sku like '%\t' or variation_sku like '%\n' or variation_sku like '%\t\n' or variation_sku like '%\n\t'";
        $list = Db::select($sql);
//        var_dump($list);die;

        foreach ($list as $k => $v) {
            $variation_sku = trim($v->variation_sku);

            $res = Db::table('shopee_order_items')->where('id', $v->id)->update(['variation_sku' => $variation_sku]);
        }
    }

    public function report_test(){
        $report = Db::table('amazon_report')->select('id','sku','user_id')->get()->toArray();
        foreach($report as $key=>$value){
            if(!$value->user_id){
                $skulist = Db::table('amazon_skulist')->where('sku',$value->sku)->pluck('user_id')->toArray();
                if($skulist){
                    $update = Db::table('amazon_report')->where('id',$value->id)->update(['user_id'=>$skulist[0]]);
                }
            }

        }
    }

    public function spu_return(){
        $order_return = Db::table('amazon_return_order')->select('id','sku')->where('spu','')->get()->toArray();
//        var_dump($order_return);die;
        foreach ($order_return as $key=>$value){
            $spu = Db::table('self_sku')->select('spu','shop_id')->where('old_sku',$value->sku)->get()->toArray();
            if(!empty($spu)){
                $update = Db::table('amazon_return_order')->where('id',$value->id)->update(['spu'=>$spu[0]->spu,'shop_id'=>$spu[0]->shop_id]);

            }

        }




        /*foreach ($order_return as $key=>$value){
            foreach ($spu as $k=>$v){
                if($v->old_sku==$value->sku){
                    echo 1;die;
                    $update = Db::table('amazon_return_order')->where('id',$value->id)->update(['spu'=>$v->spu,'shop_id'=>$v->shop_id]);
                }
            }
        }*/
    }


    public function Uptest(){


        //cloudhouse_record  

        $list = db::table('cloudhouse_record')->where('type','!=',2)->where('type','!=',9)->groupby('spu_id')->get();
        $err = [];
        foreach ($list as $v) {
            # code...
            $price = db::table('cloudhouse_custom_sku as a')->leftjoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')->where('a.spu_id',$v->spu_id)->where('b.contract_class','!=',5)->select('a.price')->first()->price??0;
            if($price<=0){
                $price = db::table('self_spu_info')->where('spu_id',$v->spu_id)->first()->unit_price??0;
            }
            if($price>0){
                // echo $v->id."\n";
                // // $np = round($v->num *  $price,2);
                // db::table('cloudhouse_record')->where('type','!=',2)->where('type','!=',9)->where('spu_id',$v->spu_id)->update(['new_price'=>$price]);
                // $err[] = $v->id.'-'.$np; 
            }else{
                $err[] ='无价格'.$v->spu_id;
            }
        
    
        }

        echo implode(',', $err);
        return;

        // //加权数量
        // $cus = db::table('self_custom_sku')->get();
        
        // foreach ($cus as $v) {
        // # code...
        //     $i['custom_sku_id'] = $v->id;
        //     $i['spu_id'] = $v->spu_id;
        //     $i['spu'] = $v->spu;
        //     $i['custom_sku'] = $v->custom_sku;
        //     $i['price'] = 0;
        //     if($v->tongan_inventory>0){
        //         $i['warehouse_id'] = 1;
        //         $i['num'] =$v->tongan_inventory;
        //         // $tongan[$v->id] = $v->tongan_inventory;
        //         db::table('inventory_total_pirce_new')->insert($i);
        //     }

        //     if($v->quanzhou_inventory>0){
        //         $i['warehouse_id'] = 2;
        //         $i['num'] =$v->quanzhou_inventory;
        //         db::table('inventory_total_pirce_new')->insert($i);
        //         // $quanzhou[$v->id] = $v->quanzhou_inventory;
        //     }
        // }

        // return 1;



        //仓库总值
        // $cus = db::table('self_custom_sku')->get();

        // $tongan = 0;
        // $quanzhou = 0;
        // $cloud = 0;
        // foreach ($cus as $v) {
        // # code...
        //     $iventory = $v->tongan_inventory+$v->quanzhou_inventory+$v->cloud_num;
        //     if($iventory>0){
        //         $price = db::table('cloudhouse_custom_sku as a')->leftjoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')->where('a.spu_id',$v->spu_id)->where('b.contract_class','!=',5)->select('a.price')->first()->price??0;
        //         if($price<=0){
        //             $price = db::table('self_spu_info')->where('spu_id',$v->spu_id)->first()->unit_price??0;
        //         }

        //         if($price>0){
        //             // $np = round($v->num *  $price,2);
        //             // db::table('inventory_total_pirce')->where('id',$v->id)->update(['new_price'=>$np]);
        //             // $err[] = $v->id; 
        //             if($v->tongan_inventory>0){
        //                 $tongan+=$v->tongan_inventory*$price;
        //             }
        //             if($v->quanzhou_inventory>0){
        //                 $quanzhou+=$v->quanzhou_inventory*$price;
        //             }
        //             if($v->cloud_num>0){
        //                 $cloud+=$v->cloud_num*$price;
        //             }
        //         }
        //     }
            
        // }

        // $arr['tongan'] = $tongan;
        // $arr['quanzhou'] = $quanzhou;
        // $arr['cloud'] = $cloud;

        // var_dump($arr);
        // return;
        //加权平均-正常
        $list = db::table('inventory_total_pirce as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->where('a.num','>',0)->where('b.type',1)->select('a.*')->get();

        $err = [];
        foreach ($list as $v) {
            # code...
 

   

        
            $price = db::table('cloudhouse_custom_sku as a')->leftjoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')->where('a.spu_id',$v->spu_id)->where('b.contract_class','!=',5)->select('a.price')->first()->price??0;
            if($price<=0){
                $price = db::table('self_spu_info')->where('spu_id',$v->spu_id)->first()->unit_price??0;
            }
            if($price>0){
                $np = round($v->num *  $price,2);
                db::table('inventory_total_pirce')->where('id',$v->id)->update(['price'=>$np]);
                // $err[] = $v->id.'-'.$np; 
            }else{
                $err[] ='无价格'.$v->custom_sku_id;
            }
        
    
        }

        echo implode(',', $err);
        return;

        //加权平均-组合
        $list = db::table('inventory_total_pirce as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->where('a.num','>',0)->where('b.type',2)->select('a.*')->get();

        $err = [];
        foreach ($list as $v) {
            # code...
            $zuhe = db::table('self_group_custom_sku')->where('custom_sku_id',$v->custom_sku_id)->get();

            $total_price = 0;
            foreach ($zuhe as $zv) {

                $zv_spu = db::table('self_custom_sku')->where('id',$zv->group_custom_sku_id)->first();
                if(!$zv_spu){
                    $err[] = '成员已被删除，组合库存sku:'.$v->custom_sku_id.'成员：'.$zv->group_custom_sku_id;

                }else{
                    $price = db::table('cloudhouse_custom_sku as a')->leftjoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')->where('a.spu_id',$zv_spu->spu_id)->where('b.contract_class','!=',5)->select('a.price')->first()->price??0;
                    if($price<=0){
                        $price = db::table('self_spu_info')->where('spu_id',$zv_spu->spu_id)->first()->unit_price??0;
                    }
                    if($price>0){
                        $np = round($v->num *  $price,2);
                        $total_price+=$np;
                        // $err[] = $v->id.'-'.$np; 
                    }else{
                        $err[] ='组合库存：'.$v->custom_sku_id.'--无价格子库存：'.$zv->group_custom_sku_id;
                    }
                }
               
            }

            db::table('inventory_total_pirce')->where('id',$v->id)->update(['price'=>$total_price]);

        }

        echo implode(',', $err);
        return;


        

        // $shops = db::table('shop')->get();
        // $e_shops = [];
        // foreach ($shops as $v) {
        //     # code...
        //     if($v->region=='EU'){
        //         $e_shops[] = $v->Id;
        //     }
        // }

        // $time = date('Y-m-d',time()-86400);
        // $list = db::table('amazon_order_item')->whereIn('shop_id',$e_shops)->where('amazon_time','>',$time)->get();

        // foreach ($list as $lv) {
        //     # code...
        //     $l_time = date('Y-m-d H:i:s',strtotime($lv->amazon_time)+(9*3600));

        //     db::table('amazon_order_item')->where('id',$lv->id)->update(['amazon_time'=>$l_time]);
        //     echo $lv->id."\n";
        // }

        // echo '完成';
        // return;

        // $table = 'self_spu_info_img';
        // // $list = db::table($table)->get();

        // // foreach ($list as $v) {
        // //     $spu = db::table('self_spu')->where('base_spu_id',$v->base_spu_id)->get();
        // //     foreach ($spu as $sv) {
        // //         # code...
        // //         $v->spu_id = $sv->id;
        // //         $iv = json_decode(json_encode($v),true);
        // //         unset($iv['id']);
        // //         db::table($table.'_a')->insert($iv);
        // //     }
        // //     # code...
        // // }

        // echo $table.'完成';
        // $list = db::table('c_ids')->where('is_in',2)->limit(2)->get();
        // $token = db::table('users')->where('Id',1)->first()->token;
        // $dds = [];
        // foreach ($list as $v) {
        //     # code...
        //     $bv = db::table('cloudhouse_location_log')->where('id',$v->ids)->first();
          
        //     if($bv){
        //         $skuData = [];
        //         $location_data = [];
        //         //生成出库清单
        //         $invetoryModel = new \App\Models\InventoryModel();
        //         $warehouse_id = db::table('cloudhouse_warehouse_location')->where('id',$bv->location_id)->first()->warehouse_id;
        //         $out_inventory['out_house'] = $warehouse_id;
        //         $out_inventory['token'] = $token;
        //         $location_data[0] = ['platform_id'=>4,'location_id'=>$bv->location_id,'num'=>$bv->num];
        //         $skuData[0] = ['custom_sku'=>$bv->custom_sku,'num'=>$bv->num,'location_data'=>$location_data,'remark'=>'程序重复入库，调整库存'];
        //         $out_inventory['skuData'] = $skuData;
        //         $out_inventory['type'] = 5;
        //         $out_inventory['platform_id'] =  4;
        //         $out_inventory['type_detail'] = 11;
        //         $out_inventory['remark'] = '程序重复入库，调整库存,订单号'.$bv->order_no;
        //         // var_dump($out_inventory);
        
        //         $out_msg = $invetoryModel->goods_transfers($out_inventory);
        //         if($out_msg['code']!=200){
        //             // db::rollback();// 回调
        //             db::table('cloudhouse_location_log')->where('id',$bv->id)->update(['change'=>$out_msg['msg']]);
        //             db::table('c_ids')->where('id',$v->id)->update(['is_in'=>2]);
        //             // $rt["ref_no"]='Z'.time().rand(100,999).'T';
        //             // $rt["msg"]= '生成出库清单失败'.$out_msg['msg'];
        //             // var_dump($rt);
        //         }else{
        //             $dds[] = $v->ids;
        //             db::table('cloudhouse_location_log')->where('id',$bv->id)->update(['change'=>1]);
        //             db::table('c_ids')->where('id',$v->id)->update(['is_in'=>1]);
        //         }

               
               
        //     }
    

        // }

        // echo implode(',',$dds);
        // $lista = db::table('cloudhouse_location_log')->where('time','like','%2023-08-16%')->get();
        // $listb = db::table('cloudhouse_location_log')->where('time','like','%2023-09-07%')->get();
        // $token = db::table('users')->where('Id',1)->first()->token;
        // // db::beginTransaction();    //开启事务
        // $dataa = [];
        // foreach ($lista as $av) {
        //     # code...
        //     $dataa[$av->custom_sku_id.'-'.$av->num.'-'.$av->location_id] =$av->id; 
        // }

        // $data = [];
        // $i = 0;
        // foreach ($listb as $bv) {
        //     # code...
        //     $key = $bv->custom_sku_id.'-'.$bv->num.'-'.$bv->location_id;
        //     if(isset($dataa[$key])){
        //         $data[] = $bv->id;
        //         //53614
                
        //         if($bv->id!=53614){
        //             $i++;
        //             $skuData = [];
        //             $location_data = [];
        //             //生成出库清单
        //             $invetoryModel = new \App\Models\InventoryModel();
        //             $warehouse_id = db::table('cloudhouse_warehouse_location')->where('id',$bv->location_id)->first()->warehouse_id;
        //             $out_inventory['out_house'] = $warehouse_id;
        //             $out_inventory['token'] = $token;
        //             $location_data[0] = ['platform_id'=>4,'location_id'=>$bv->location_id,'num'=>$bv->num];
        //             $skuData[0] = ['custom_sku'=>$bv->custom_sku,'num'=>$bv->num,'location_data'=>$location_data,'remark'=>'8月16-9月07程序重复入库，调整库存'];
        //             $out_inventory['skuData'] = $skuData;
        //             $out_inventory['type'] = 5;
        //             $out_inventory['platform_id'] =  4;
        //             $out_inventory['type_detail'] = 11;
        //             $out_inventory['update_cause'] = '8月16-9月07程序重复入库，调整库存';
        //             // var_dump($out_inventory);
            
        //             $out_msg = $invetoryModel->goods_transfers($out_inventory);
        //             if($out_msg['code']!=200){
        //                 // db::rollback();// 回调
        //                 db::table('cloudhouse_location_log')->where('id',$bv->id)->update(['change'=>$out_msg['msg']]);
        //                 // $rt["ref_no"]='Z'.time().rand(100,999).'T';
        //                 // $rt["msg"]= '生成出库清单失败'.$out_msg['msg'];
        //                 // var_dump($rt);
        //             }else{
        //                 db::table('cloudhouse_location_log')->where('id',$bv->id)->update(['change'=>1]);
        //             }

            
        //         }
        //     }

        // }
        // // db::commit();
        // echo $i;
        return;

        // $list = db::table('cloudhouse_contract as a')->leftjoin('cloudhouse_contract_total as b','a.anok_id','=','b.anok_id')->where('b.contract_type','成品采购')->get();
        // foreach ($list as $v) {
        //     $base_spu_id = db::table('self_spu')->where('id',$v->spu_id)->first()->base_spu_id??0;
        //     if($base_spu_id>0&&$v->one_price>0){
        //         $i['unit_price'] = $v->one_price;
        //         $i['status'] = 2;
        //         $info = db::table('self_spu_info')->where('base_spu_id',$base_spu_id)->first();
        //         if($info){
        //             db::table('self_spu_info')->where('base_spu_id',$base_spu_id)->update($i);
        //         }else{
        //             $i['base_spu_id'] = $base_spu_id;
        //             db::table('self_spu_info')->insert($i);
        //         }
        //     }
        // }
        // $list = db::table('cloudhouse_contract')->where('rule','')->get();
        // // var_dump($list);
        // // return;
        // foreach ($list as $v) {
        //     # code...
        //     $av = json_decode(json_encode($v),true);
        //     // $v->num_info = '';
        //     $num_info = [];
        //     $rule = [];
        //     if($v->XXS>0){
        //         $num_info['XXS'] = $v->XXS;
        //         $rule[] = 'XXS';
        //     }
        //     if($v->XS>0){
        //         $num_info['XS'] = $v->XS;
        //         $rule[] = 'XS';
        //     }
        //     if($v->S>0){
        //         $num_info['S'] = $v->S;
        //         $rule[] = 'S';
        //     }
        //     if($v->M>0){
        //         $num_info['M'] = $v->M;
        //         $rule[] = 'M';
        //     }
        //     if($v->L>0){
        //         $num_info['L'] = $v->L;
        //         $rule[] = 'L';
        //     }
        //     if($v->XL>0){
        //         $num_info['XL'] = $v->XL;
        //         $rule[] = 'XL';
        //     }
        //     if($av['2XL']>0){
        //         $num_info['2XL'] = $av['2XL'];
        //         $rule[] = '2XL';
        //     }
        //     if($av['3XL']>0){
        //         $num_info['3XL'] = $av['3XL'];
        //         $rule[] = '3XL';
        //     }
        //     if($av['4XL']>0){
        //         $num_info['4XL'] = $av['4XL'];
        //         $rule[] = '4XL';
        //     }
        //     if($av['5XL']>0){
        //         $num_info['5XL'] = $av['5XL'];
        //         $rule[] = '5XL';
        //     }
        //     if($av['6XL']>0){
        //         $num_info['6XL'] = $av['6XL'];
        //         $rule[] = '6XL';
        //     }
        //     if($av['7XL']>0){
        //         $num_info['7XL'] = $av['7XL'];
        //         $rule[] = '7XL';
        //     }
        //     if($av['8XL']>0){
        //         $num_info['8XL'] = $av['8XL'];
        //         $rule[] = '8XL';
        //     }

        //     $up['rule'] = implode(',',$rule);
        //     $up['num_info'] = json_encode($num_info);

        //     db::table('cloudhouse_contract')->where('id',$v->id)->update($up);

        // }
        // $list = db::table('amazon_place_order_detail')->get();
        // foreach ($list as $v) {
        //     $skus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
        //     if($skus){
        //         $info = db::table('self_spu_info')->where('base_spu_id',$skus->base_spu_id)->first();
        //         if($info){
        //             db::table('amazon_place_order_detail')->where('id',$v->id)->update(['suppliers_price'=>$info->unit_price]);
        //         }

        //     }
        //     # code...
        // }

        // echo '完成';
      //  $list = db::table('goods_transfers as a')->leftjoin('goods_transfers_detail as b','a.order_no','=','b.order_no')->where('a.createtime','like','%2023-08-26%')->where('a.user_id',1)->where('a.in_house',1)->delete();
        // foreach ($list as $v) {
        // //     # code...
        // //   $one = db::table('cloudhouse_location_num')->where('custom_sku_id',$v->custom_sku_id)->where('location_id',$v->location_id)->first();

        // //   if($one){
        // //     $num = $one->num - $v->num;
        // //     var_dump($num);
        // //     db::table('cloudhouse_location_num')->where('id',$one->id)->update(['num'=>$num]);
        // //   }

        // }
        // db::beginTransaction();    
        // $a = db::table('local_sql')->first();
        // $b = $a->name - 5;
        // db::table('local_sql')->update(['name'=>$b]);

        // $c = db::table('local_sql')->first();
        // $d = $c->name - 5;
        // db::table('local_sql')->update(['name'=>$d]);
        // db::commit();

        // $list = db::table('cloudhouse_location_num_copy5')->get();
        // foreach ($list as $v) {
        //     $md5 = $v->custom_sku_id.'-'.$v->location_id.'-'.$v->platform_id;
        //     db::table('cloudhouse_location_num_copy5')->where('id',$v->id)->update(['md5'=>$md5]);
        //     # code...
        // }
        return;
        //库存不符数据
        // $warehouse_id = 2;
        // $tongan_arr =  db::table('cloudhouse_location_num as a')->leftjoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')->where('b.warehouse_id',$warehouse_id)->select(db::raw('sum(a.num) as num'),'a.custom_sku_id')->groupby('a.custom_sku_id')->get();
        // $cus_arr = db::table('self_custom_sku')->where('quanzhou_inventory','>',0)->get();
        // $cus_arr_t = [];
        // foreach ($cus_arr as $cv) {
        //     # code...
        //     if($warehouse_id==2){
        //         $cus_arr_t[$cv->id] = $cv->quanzhou_inventory;
        //     }
        //     if($warehouse_id==1){
        //         $cus_arr_t[$cv->id] = $cv->tongan_inventory;
        //     }
        // }


        // foreach ($tongan_arr as $v) {
        //     $tongan_err = [];
        //     if(isset($cus_arr_t[$v->custom_sku_id])){
        //         if($v->num!=$cus_arr_t[$v->custom_sku_id]){
        //             $tongan_err['custom_sku_id'] = $v->custom_sku_id;
        //             $tongan_err['custom_num'] = $cus_arr_t[$v->custom_sku_id];
        //             $tongan_err['location_num'] = $v->num;
        //             $tongan_err['warehouse_id'] =$warehouse_id;
        //             db::table('err_inventory')->insert($tongan_err);
        //         }
        //     }else{
        //         if($v->num>0){
        //             $tongan_err['custom_sku_id'] = $v->custom_sku_id;
        //             $tongan_err['custom_num'] = 0;
        //             $tongan_err['location_num'] = $v->num;
        //             $tongan_err['warehouse_id'] =$warehouse_id;
        //             db::table('err_inventory')->insert($tongan_err);
        //         }
        //     }
    
        //     # code...
        // }



        // $lists = db::table('goods_transfers_box_detail')->whereIn('box_id',[14448,14423])->get();

        // $new_list = [];
        // foreach ($lists as $va) {
        //     # code...
        //     $key = $va->custom_sku_id.'-'.$va->location_ids;
        //     if(isset($new_list[$key]['box_num'])){
        //         $new_list[$key]['box_num']+=$va->box_num;
        //     }else{
        //         $new_list[$key]['box_num']=$va->box_num;
        //     }

        //     $new_list[$key]['location_ids'] = $va->location_ids;
        //     $new_list[$key]['custom_sku_id'] = $va->custom_sku_id;
        // }



        // // var_dump($list);
    
        // foreach ($new_list as $v) {
        //     # code...
        //     $num = $v['box_num'];
        //     $amazon = db::table('cloudhouse_location_num')->where('custom_sku_id',$v['custom_sku_id'])->where('location_id',$v['location_ids'])->where('platform_id',5)->first();

        //     $other = db::table('cloudhouse_location_num')->where('custom_sku_id',$v['custom_sku_id'])->where('location_id',$v['location_ids'])->where('platform_id',4)->first();
        //     $is_num = false;
        //     if($amazon){
        //             if($num>$amazon->num){
        //                 $dec_num = $num-$amazon->num;
        //                 $is_num = true;
        //                 db::table('cloudhouse_location_num')->where('id', $amazon->id)->update(['num'=>$num,'change'=>8]);
        //             }else{
        //                 $dec_num = 0;
        //             }
        //     }else{
        //         $dec_num = $num;
        //     }
        //     if($other){
        //         if($dec_num>0){
        //             $o_num = $other->num - $dec_num;
        //             db::table('cloudhouse_location_num')->where('id', $other->id)->update(['num'=>$o_num,'change'=>8]);
        //             if(!$is_num){
        //                 //新增亚马逊库位数据
        //                 $is = json_decode(json_encode($other),true);
        //                 unset($is['id']);
        //                 unset($is['warehouse_id']);
        //                 $is['platform_id'] = 5;
        //                 $is['num'] = $dec_num;
        //                 $is['change'] = 9;
        //                 db::table('cloudhouse_location_num')->insert($is);
        //             }
        //         }
                
        //     }else{
        //         $err[] = $v['custom_sku_id'];
        //     }
            

        // }
        // var_dump($err);
        //切割库存
//             $table = 'cloudhouse_location_num';
//             # code...
//             $list =  db::table( $table.' as a')->leftjoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')->where('a.spu_id',244)->where
//             ('platform_id',12)->where('change','!=',186)->where('b.warehouse_id',2)->select('a.*','b.warehouse_id')
//                     ->get();
//             $model =  new \App\Models\BaseModel();
//             foreach ($list as $bv) {
//                 # code...
//                 $locks = $model->lock_inventory_dd($bv->custom_sku_id,12);
//                 $lock_num = 0;
//                 if(isset($locks[$bv->custom_sku_id][$bv->location_id])){
//                     $lock_num = $locks[$bv->custom_sku_id][$bv->location_id];
//                 }
//                 //可用库存 = 总库存-锁定库存
//                 $use_num = $bv->num - $lock_num;
//                 if($use_num>0){
//                     //可用库存按比例分配
// //                    $rates = db::table('test_inventory_rateb')->where('custom_sku_id',$bv->custom_sku_id)->where('warehouse_id',$bv->warehouse_id)->first();
// //                    if(!$rates){
// //                        return;
// //                    }
//                     //计算亚马逊占用数量
//                     $amazon_num = ceil($use_num * 0.5);
//                     //其他库存 = 总-亚马逊
//                     $other_num  = $bv->num-$amazon_num;
//                     //修改本条数据为其他库存 并且平台修改为公共库位
//                     db::table($table)->where('id',$bv->id)->update(['num'=>$other_num,'change'=>816]);
//                     //新增亚马逊库位数据
//                     $is = json_decode(json_encode($bv),true);
//                     unset($is['id']);
//                     unset($is['warehouse_id']);
//                     $is['platform_id'] = 5;
//                     $is['num'] = $amazon_num;
//                     $is['change'] = 816;
//                     db::table($table)->insert($is);
//                 }
//             }

        // //将价格同步到spuinfo
        // $list =  db::table('sputest_price')->get();
        // foreach ($list as $v) {
        //     $respeat = db::table('self_spu_info')->where('base_spu_id',$v->base_spu_id)->first();
        //     if($respeat){
        //         db::table('self_spu_info')->where('base_spu_id',$v->base_spu_id)->update(['unit_price'=>$v->price]);
        //     }else{
        //         db::table('self_spu_info')->insert(['unit_price'=>$v->price,'base_spu_id'=>$v->base_spu_id]);
        //     }
        //     # code...
        // }

        // return;

        // //将价格同步到库位库存
        // $list = db::table('inventory_total_pirce')->get();
        // $ids = [];
        // foreach ($list as $v) {
        //     $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
        //     if($cus){
        //         $base_spu_id = $cus->base_spu_id;
        //         $one = db::table('sputest_price')->where('base_spu_id',$base_spu_id)->first();
        //         if($one){
        //             $all_pirce = round($v->num * $one->price,2);
        //             db::table('inventory_total_pirce')->where('id',$v->id)->update(['price'=>$all_pirce]);
        //             $ids[] = $v->id;
        //         }
        //     }

        //     # code...
        // }
        // var_dump($ids);
        // return;


        // //更新总资产
        // $list = db::table('self_custom_sku')->get();
        // // $list = db::table('self_custom_sku')->where('quanzhou_inventory','>',0)->get();
        // // $list = db::table('self_custom_sku')->where('cloud_num','>',0)->get();

        // $prices = [];
        // $spu_info = db::table('self_spu_info')->get();
        // foreach ($spu_info as $spv) {
        //     # code...
        //     $prices[$spv->base_spu_id] = $spv->unit_price;
        // }
        // $tongan = 0;
        // $quanzhou = 0;
        // $cloud = 0;

        // foreach ($list as $v) {
        //     # code...
        //     // $spus = db::table('self_spu_info')->where('base_spu_id',$v->base_spu_id)->first();
        //     // if($spus){
        //     //     $price = $spus->unit_price; 
        //     // }
        //     $price = 0;
        //     if(isset($prices[$v->base_spu_id])){
        //         $price =$prices[$v->base_spu_id];
        //     }

        //      $tongan += $price*$v->tongan_inventory;
        //      $quanzhou += $price*$v->quanzhou_inventory;
        //      $cloud += $price*$v->cloud_num;
        // }

        // $data['tongan'] = $tongan;
        // $data['quanzhou'] = $quanzhou;
        // $data['cloud'] = $cloud;
        // var_dump($data);
        // return;
        

        // $list = db::table('self_spu')->where('type',2)->get();
        // foreach ($list as $v) {
        //     # code...
        //     $i['base_spu'] = $v->spu;
        //     $i['user_id'] =$v->user_id;
        //     $i['create_time'] = $v->create_time;
        //     $i['is_new'] = 2;
        //     $i['one_cate_id'] =0;
        //     $i['two_cate_id'] = 0;
        //     $i['three_cate_id'] = 0;
        //     $i['status'] = 1;
        //     $i['num'] = 0;
        //     $base_spu_id = db::table('self_base_spu')->insertGetId($i);
        //     db::table('self_spu')->where('id',$v->id)->update(['base_spu_id'=>$base_spu_id]);
        //     db::table('self_custom_sku')->where('spu_id',$v->id)->update(['base_spu_id'=>$base_spu_id]);
        // }
        // echo '完成';
        // return;

        //比例

        // $list = db::table('test_inventory_rate')->where('all','<','1')->get();
        // // var_dump($list);
        // foreach ($list as $v) {
        //     # code...
        //     $spu = $v->spu;
        //     $spus = db::table('self_spu')->where('spu',$spu )->orwhere('old_spu',$spu )->first();
        //     $spu_id = $spus->id;
        //     $cus = db::table('self_custom_sku')->where('spu_id',$spu_id)->get();
        //     foreach ($cus as $cv) {
        //         # code...
        //         $i['custom_sku'] = $cv->custom_sku;
        //         $i['custom_sku_id'] =  $cv->id;
        //         $i['spu'] =$spu;
        //         $i['color'] = $cv->color;
        //         $i['size'] = $cv->size;
        //         $i['warehouse_id'] = $v->warehouse_id;
        //         $vs = json_decode(json_encode($v),true);

        //         $s = ['CFWTX00033','CUWPO01444','CFWTX00039','CFWTX00040','CFWZZ00010'];
        //         if(in_array($spu, $s)){
        //             if($cv->size=='2XL'){
        //                 $i['num'] = $vs['3xl'];
        //             }
        //             if($cv->size=='XL'){
        //                 $i['num'] = $vs['2xl'];
        //             }
        //             if($cv->size=='L'){
        //                 $i['num'] = $vs['xl'];
        //             }
        //             if($cv->size=='M'){
        //                 $i['num'] = $vs['l'];
        //             }
        //             if($cv->size=='S'){
        //                 $i['num'] = $vs['m'];
        //             }
        //         }else{
        //             if($cv->size=='3XL'){
        //                 $i['num'] = $vs['3xl'];
        //             }
        //             if($cv->size=='2XL'){
        //                 $i['num'] = $vs['2xl'];
        //             }
        //             if($cv->size=='XL'){
        //                 $i['num'] = $vs['xl'];
        //             }
        //             if($cv->size=='L'){
        //                 $i['num'] = $vs['l'];
        //             }
        //             if($cv->size=='M'){
        //                 $i['num'] = $vs['m'];
        //             }
        //         }
             
               

        //         db::table('test_inventory_rateb')->insert($i);
        //     }
        //     // $i['base_spu'] = $v->spu;
        //     // $i['user_id'] =$v->user_id;
        //     // $i['create_time'] = $v->create_time;
        //     // $i['is_new'] = 2;
        //     // $i['one_cate_id'] =0;
        //     // $i['two_cate_id'] = 0;
        //     // $i['three_cate_id'] = 0;
        //     // $i['status'] = 1;
        //     // $i['num'] = 0;
        //     // $base_spu_id = db::table('self_base_spu')->insertGetId($i);
        //     // db::table('self_spu')->where('id',$v->id)->update(['base_spu_id'=>$base_spu_id]);
        //     // db::table('self_custom_sku')->where('spu_id',$v->id)->update(['base_spu_id'=>$base_spu_id]);
        // }

        






        // $table = 'cloudhouse_location_num_c';

        // //修改库存库位数据为公共库位
        // // db::table($table)->update(['platform_id'=>4]);

        // //修改要求全部的数据为亚马逊
        // // $list = db::table('cloudhouse_location_num_c')->get();
        // $list = db::table('test_inventory_rate')->get();
        // foreach ($list as $v) {
        //     # code...
        //     db::table( $table.' as a')->leftjoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')->where('a.spu_id',$v->spu_id)->where('a.platform_id',4)->where('b.warehouse_id',$v->warehouse_id)->update(['platform_id'=>5,'change'=>1]);
        // }

        // //分配剩余的数据
        // $cus = db::table('test_inventory_rateb')->get()->toarray();
        // // $cus_ids = array_column($cus,'custom_sku_id');
        // $model =  new \App\Models\BaseModel();

        // foreach ($cus as $cv) {
        //     # code...
        //     $listb = db::table( $table.' as a')->leftjoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')->where('a.custom_sku_id',$cv->custom_sku_id)->where('b.warehouse_id',$cv->warehouse_id)->where('a.num','>',0)->select('a.*')->get();
        //     foreach ($listb as $bv) {
        //         # code...
    
        //         $locks = $model->lock_inventory_dd($bv->custom_sku_id);
        //         $lock_num = 0;
        //         if(isset($locks[$bv->custom_sku_id][$bv->location_id])){
        //             $lock_num = $locks[$bv->custom_sku_id][$bv->location_id];
        //         }
        //         //可用库存 = 总库存-锁定库存
        //         $use_num = $bv->num - $lock_num;
        //         if($use_num>0){
        //             //可用库存按比例分配
        //             $amazon_num = ceil($use_num * $cv->num);
        //             //其他库存 = 总-亚马逊
        //             $other_num  = $bv->num-$amazon_num;
        //             //修改本条数据为其他库存 并且平台修改为公共库位
        //             db::table($table)->where('id',$bv->id)->update(['platform_id'=>4,'num'=>$other_num,'change'=>1]);
        //             //新增亚马逊库位数据
        //             $is = json_decode(json_encode($bv),true);
        //             unset($is['id']);
        //             $is['platform_id'] = 5;
        //             $is['num'] = $amazon_num;
        //             $is['change'] = 2;
        //             db::table($table)->insert($is);
        //         }
        //     }
        // }

        echo '完成';
        return;
    }

    

//    public function mytest()
//    {
//       $t = db::table('cloudhouse_warehouse_location')->get();
//        try {
//            db::beginTransaction();
//            foreach ($t as $v){
//                if(!empty($v->platform_ids)){
//                    $pid = json_decode($v->platform_ids, true);
//                    $pmdl = db::table('platform')->whereIn('identifying', $pid)->get()->toArrayList();
//                    $name = array_column($pmdl, 'name');
//                    $name = implode(',', $name);
//                    db::table('cloudhouse_warehouse_location')->where('id', $v->id)->update(['platform_name' => $name]);
//                }
//            }
//
//            db::commit();
//            return '修改成功！';
//        }catch (\Exception $e){
//            db::rollback();
//            return '错误:'.$e->getMessage();
//        }
//
//    }

    /**
     * @Desc:导入链接策略
     * @return string
     * @author: Liu Sinian
     * @Time: 2023/7/25 9:46
     */
//    public function mytest()
//    {
//        try {
//            // 获取所有请求参数
//            $params = $this->request->all();
//            $file = $params['file'];
//            if (empty($file)) {
//                throw new \Exception('导入失败，文件为空！', 400);
//            }
//            //获取文件后缀名
//            $extension = $file->getClientOriginalExtension();
//            if ($extension == 'csv') {
//                $PHPExcel = new \PHPExcel_Reader_CSV();
//            } elseif ($extension == 'xlsx') {
//                $PHPExcel = new \PHPExcel_Reader_Excel2007();
//            } else {
//                $PHPExcel = new \PHPExcel_Reader_Excel5();
//            }
//
//            if (!$PHPExcel->canRead($file)) {
//                throw new \Exception('导入失败，Excel文件错误', 400);
//            }
//            $PHPExcelLoad = $PHPExcel->load($file);
//
//            $Sheet = $PHPExcelLoad->getSheet(0);
//            /**取得一共有多少行*/
//            $allRow = $Sheet->getHighestRow();
//
//            $allRow = $allRow + 1;
//            //循环插入流量数据
//            $i = 0;
//            DB::beginTransaction();
//            // 循环处理数据变更
//            $baseModel = new BaseModel();
//            for ($j = 2; $j < $allRow; $j++) {
//                // 获取格式化值
//                $shopId = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
////                var_dump($shopId);exit();
//                $fasin = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
//                $strategy = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
//                db::table('amazon_fasin_bind')->where('fasin', $fasin)->where('shop_id', $shopId)->update(['strategy' => $strategy]);
//            }
//
//            db::commit();
//            return '导入成功！';
//        }catch (\Exception $e){
//            db::rollback();
//            return '错误：'.$e->getMessage().';位置'.$e->getLine();
//        }
//    }

    /**
     * @Desc:库位增加平台
     * @return string
     * @author: Liu Sinian
     * @Time: 2023/7/26 17:45
     */
//    public function mytest()
//    {
//        $i = 0;
//        try {
//            $params = $this->request->all();
//            if (!isset($params['platform_identifying']) || empty($params['platform_identifying'])){
//                throw new \Exception('未给定平台标识！');
//            }
//            $locationMdl = db::table('cloudhouse_warehouse_location')->whereNotNull('platform_ids')->get();
//            $platformMdl = db::table('platform')->where('identifying', $params['platform_identifying'])->first();
//            if (empty($platformMdl)){
//                throw new \Exception('未查询到该平台数据！');
//            }
//            db::beginTransaction();
//            foreach ($locationMdl as $v){
//                $i = $v->id;
//                $pid = json_decode($v->platform_ids, true);
//                if (!is_array($pid)){
//                    continue;
//                }
//                if (in_array("C", $pid)){
//                    $name = explode(',', $v->platform_name);
//                    array_push($name, $platformMdl->name);
//                    $name = implode(',', array_unique($name));
//                    array_push($pid, $params['platform_identifying']);
//                }
//                $platMdl = db::table('platform')->whereIn('identifying', $pid)->get()->toArrayList();
//                $pid = array_column($platMdl, 'identifying');
//                $pid = json_encode($pid);
//                $re = db::table('cloudhouse_warehouse_location')->where('id', $v->id)->update(['platform_name' => $name, 'platform_ids' => $pid]);
//                if ($re){
//                    echo "库位id:".$v->id."数据更新成功！";
//                }else{
//                    echo "库位id:".$v->id."数据更新失败！";
//                }
//            }
//            db::commit();
//            return "更新完成！";
//        }catch (\Exception $e){
//            db::rollback();
//            return "更新错误！原因：".$e->getMessage().'；错误id:'.$i.'；位置：'.$e->getLine();
//        }
//
//    }

//    public function mytest()
//    {
//        try{
//            $id = [21258,21261,21268,21278,21279,21280,21284,21295,21296,21297,21298,21299,21300,21301,21302,21303,21304,21305,21306,21307,21313,21314,21315,21316,21339,21340,21341,21342];
////            $params = $this->request->all();
////            $log = db::table('cloudhouse_location_log')->whereIn('id', $id)->get();
////            db::beginTransaction();
////            foreach ($log as $v){
////                $a = [
////                    'location_id' => $v->location_id,
////                    'num' => $v->num,
////                    'custom_sku' => $v->custom_sku,
////                    'custom_sku_id' => $v->custom_sku_id,
////                    'spu' => $v->spu,
////                    'spu_id' => $v->spu_id,
////                    'type' => 2,
////                    'time' => $v->time,
////                    'order_no' => $v->order_no,
////                    'user_id' => $v->user_id,
////                    'remark' => '库存移动日志拆分处理 下架',
////                ];
////                $id = db::table('cloudhouse_location_log')->insertGetId([
////                    'location_id' => $v->location_id,
////                    'num' => $v->num,
////                    'custom_sku' => $v->custom_sku,
////                    'custom_sku_id' => $v->custom_sku_id,
////                    'spu' => $v->spu,
////                    'spu_id' => $v->spu_id,
////                    'type' => 2,
////                    'time' => $v->time,
////                    'order_no' => $v->order_no,
////                    'user_id' => $v->user_id,
////                    'remark' => '库存移动日志拆分处理 下架',
////                ]);
////
////                if (empty($id)){
////                    throw new \Exception('新增下架日志失败！原有日志Id：'.$v->id);
////                }
////                $id = db::table('cloudhouse_location_log')->insertGetId([
////                    'location_id' => $v->target_location_id,
////                    'num' => $v->num,
////                    'custom_sku' => $v->custom_sku,
////                    'custom_sku_id' => $v->custom_sku_id,
////                    'spu' => $v->spu,
////                    'spu_id' => $v->spu_id,
////                    'type' => 1,
////                    'time' => $v->time,
////                    'order_no' => $v->order_no,
////                    'user_id' => $v->user_id,
////                    'remark' => '库存移动日志拆分处理 上架',
////                ]);
////                if (empty($id)){
////                    throw new \Exception('新增下架日志失败！原有日志Id：'.$v->id);
////                }
////            }
////            $log = db::table('cloudhouse_location_log')->whereIn('id', $id)->delete();
////            db::commit();
//            return '处理成功！';
//        }catch (\Exception $e){
////            db::rollback();
//            return '失败！原因：'.$e->getMessage().'；位置：'.$e->getLine();
//        }
//    }

//    public function mytest()
//    {
//        try {
//            // 获取所有请求参数
//            $params = $this->request->all();
//            $file = $params['file'];
//            if (empty($file)) {
//                throw new \Exception('导入失败，文件为空！', 400);
//            }
//            //获取文件后缀名
//            $extension = $file->getClientOriginalExtension();
//            if ($extension == 'csv') {
//                $PHPExcel = new \PHPExcel_Reader_CSV();
//            } elseif ($extension == 'xlsx') {
//                $PHPExcel = new \PHPExcel_Reader_Excel2007();
//            } else {
//                $PHPExcel = new \PHPExcel_Reader_Excel5();
//            }
//
//            if (!$PHPExcel->canRead($file)) {
//                throw new \Exception('导入失败，Excel文件错误', 400);
//            }
//            $PHPExcelLoad = $PHPExcel->load($file);
//
//            $Sheet = $PHPExcelLoad->getSheet(0);
//            /**取得一共有多少行*/
//            $allRow = $Sheet->getHighestRow();
//
//            $allRow = $allRow + 1;
//            //循环插入流量数据
//            $i = 0;
//
////            if(!(isset($params['warehouse_name']) && !empty($params['warehouse_name']))){
////                throw new \Exception( '导入失败，缺少仓库名称', 400);
////            }
//
//            // 打印未查询到的sku
//            $emptySku = array();
//            DB::beginTransaction();
//            // 循环处理数据变更
//            $baseModel = new BaseModel();
//            for ($j = 2; $j < $allRow; $j++) {
//                // 获取格式化值
//                $shopId = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
//                $fasin = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
//                $zd = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
////                var_dump($zd);exit();
//                db::table('amazon_fasin_bind')->where('shop_id')->where('fasin', $fasin)->update(['strategy' => $zd]);
//            }
//            db::commit();
//            return '处理成功！';
//        }catch (\Exception $e){
//            db::rollback();
//            return '失败！原因：'.$e->getMessage().'；位置：'.$e->getLine();
//        }
//    }

//    public function mytest()
//    {
//        // 打印出打印机列表
//        $getprt = printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED);
//        $printers = serialize($getprt);
//        $printers = unserialize($printers);
////print_r($printers);
//        echo '<select name="printers">';
//        foreach ($printers as $PrintDest)
//            echo "<option value=" . $PrintDest["NAME"] . ">" . explode(",", $PrintDest["DESCRIPTION"])[1] . "</option>";
//        echo '</select>';
//
//    }

    public function importSupplier()
    {
        try {
            // 获取所有请求参数
            $params = $this->request->all();
            $file = $params['file'];
            if (empty($file)) {
                throw new \Exception('导入失败，文件为空！', 400);
            }
            //获取文件后缀名
            $extension = $file->getClientOriginalExtension();
            if ($extension == 'csv') {
                $PHPExcel = new \PHPExcel_Reader_CSV();
            } elseif ($extension == 'xlsx') {
                $PHPExcel = new \PHPExcel_Reader_Excel2007();
            } else {
                $PHPExcel = new \PHPExcel_Reader_Excel5();
            }

            if (!$PHPExcel->canRead($file)) {
                throw new \Exception('导入失败，Excel文件错误', 400);
            }
            $PHPExcelLoad = $PHPExcel->load($file);

            $Sheet = $PHPExcelLoad->getSheet(0);
            /**取得一共有多少行*/
            $allRow = $Sheet->getHighestRow();

            $allRow = $allRow + 1;
            //循环插入流量数据
            $i = 0;
            DB::beginTransaction();
            // 循环处理数据变更
            $baseModel = new BaseModel();
            $error = '';
            for ($j = 2; $j < $allRow; $j++) {
                // 获取格式化值
                $supplierName = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
                $payee = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                $bank_card_number = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                $bank_name = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                $supplier = db::table('suppliers')
                    ->where('name', $supplierName)
                    ->first();
                if (empty($supplier)){
                    if (empty($supplier)){
                        $error .= '第'.$j.'行供应商'.$supplierName.'不存在！';
                    }
                }else{
                    if (empty($supplier->payee)){
                        $supplier = db::table('suppliers')
                            ->where('name', $supplierName)
                            ->update([
                                'payee' => $payee ?? '',
                                'bank_name' => $bank_name ?? '',
                                'bank_card_number' => $bank_card_number ?? ''
                            ]);
                        if (empty($supplier)){
                            $error .= '第'.$j.'行保存失败！';
                        }
                    }
                }
            }

            db::commit();
            return '导入成功！'.$error;
        }catch (\Exception $e){
            db::rollback();
            return '错误：'.$e->getMessage().';位置'.$e->getLine();
        }
    }

    public function printPdf()
    {
        $html = '
<table cellspacing="0" cellpadding="1" border="1">
<tr>
<td width="150"> SKU</td>
<td width="40">图片</td>
<td width="100"> 库存sku</td>
<td width="120"> 中文名</td>
<td width="40"> fnsku</td>
<td width="33"> 同安自发货库存</td>
<td width="33"> 同安fba库存</td>
<td width="33"> 泉州仓库存</td>
</tr>
</table>
';
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'tcpdf' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . 'tcpdf_include.php');
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // 设置文档信息
        $pdf->SetCreator('L');
        $pdf->SetAuthor('L');
        $pdf->SetTitle('');
        $pdf->SetSubject('');
        $pdf->SetKeywords('TCPDF, PDF, PHP');

        // 设置页眉和页脚信息
        $pdf->SetHeaderData('', 0, '', '', [0, 0, 0], [255, 255, 255]);
        $pdf->setFooterData([0, 0, 0], [255, 255, 255]);

        // 设置页眉和页脚字体
        $pdf->setHeaderFont(['stsongstdlight', '', '10']);
        $pdf->setFooterFont(['helvetica', '', '8']);

        //删除预定义的打印 页眉/页尾
//            $pdf->setPrintHeader($result['is_header'] ?? false);
//            $pdf->setPrintFooter($result['is_footer'] ?? false);

        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');

        // 设置字体
//            $pdf->setFont('times');

        // 设置间距
        $pdf->SetMargins(10, 15, 15);//页面间隔
        $pdf->SetHeaderMargin(5);//页眉top间隔
        $pdf->SetFooterMargin(5);//页脚bottom间隔

        // 设置分页
        $pdf->SetAutoPageBreak(TRUE, 15);
        $pdf->setFontSubsetting(true);

        // set default font subsetting mode
        $pdf->setFontSubsetting(true);

        //设置字体 stsongstdlight支持中文
        $pdf->SetFont('stsongstdlight', '', 8);

        $pdf->Ln(5);
        // 设置密码
//            $pdf->SetProtection($permissions = array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass = '123456', $owner_pass = null, $mode = 0, $pubkeys = null );

        //第一页
        $pdf->AddPage();
        $pdf->writeHTML($html, true, false, true, true, 'center');


        //输出PDF
        $pdf->Output(public_path() . DIRECTORY_SEPARATOR . 'pdf' . DIRECTORY_SEPARATOR .'购销合同.pdf', 'D');//I输出、D下载
    }

//    public function mytest()
//    {
//        $contractSpu = db::table('cloudhouse_contract')->get();
//        foreach ($contractSpu as $v){
//            if (!empty($v->num_info)){
//                $numInfo = json_decode($v->num_info, true);
////                $rule = implode(',', array_keys($numInfo));
//                $rule = [];
//                foreach ($numInfo as $s => $n){
//                    if ($n > 0){
//                        $rule[] = $s;
//                    }
//                }
//                $rule = implode(',', array_unique($rule));
//                $update = db::table('cloudhouse_contract')
//                    ->where('id', $v->id)
//                    ->update(['rule' => $rule]);
//            }
//        }
//        return true;
//    }

    public function saveContractPdfFile()
    {
        $contractMdl = db::table('cloudhouse_contract_total')->get();
        $msg = '';
        $err = '';
        foreach ($contractMdl as $v){
            $contractNo = $v->contract_no;
            // 合同打印加入队列
            $data = [
                'title' => '购销合同',
                'type' => '购销合同-服装范本-打印',
                'user_id' => 527,
                'print_type' => 1,
                'contract_no' => $contractNo
            ];
            $job = new SaveContractPdfController();
            try {
                $job::runJob($data);
                $msg .= $contractNo.'服装范本打印成功！';
            }catch (\Exception $e){
                $err .= $contractNo.'服装范本打印失败！'.$e->getMessage();
            }

            $data = [
                'title' => '购销合同',
                'type' => '购销合同-铁艺范本-打印',
                'user_id' => 527,
                'print_type' => 2,
                'contract_no' => $contractNo
            ];
            $job::runJob($data);
            try {
                $job::runJob($data);
                $msg .= $contractNo.'铁艺范本打印成功！';
            }catch (\Exception $e){
                $err .= $contractNo.'铁艺范本打印失败！'.$e->getMessage();
            }
        }
        return ['success' => $msg, 'error' => $err];
    }

    public function updateContractInfo()
    {
        try {
            db::beginTransaction();
            $params = $this->request->all();
            if (!isset($params['contract_no'])){
                throw new \Exception('未指定更正的合同号！');
            }
//            $contractMdl = db::table('cloudhouse_contract as a')
//                ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
//                ->where('b.contract_class', 0)
//                ->get(['a.*']);
            $contractMdl = db::table('cloudhouse_contract')
                ->where('contract_no', $params['contract_no'])
                ->get();
            if ($contractMdl->isEmpty()){
                throw new \Exception('合同数据为空！');
            }
            $sizeArr = ['XXS','XS','S','M','L','XL','2XL','3XL','4XL','5XL','6XL','7XL','8XL'];
            $customSkuMdl = db::table('self_custom_sku')
                ->get();
            $customList = [];

            foreach ($customSkuMdl as $cus){
                $key = $cus->spu_id.'-'.$cus->color.'-'.$cus->size;
                $customList[$key] = $cus;
            }

            $totalList = [];
            $updateSkuList = [];
            $error = '';
            foreach ($contractMdl as $v){
                $sizeInfo = [];
                $rule = [];
                $totalPrice = 0;
                $totalCount = 0;
                foreach ($sizeArr as $s){
                    if ($v->$s > 0){
                        $key = $v->spu_id.'-'.$v->color_identifying.'-'.$s;
                        $sizeInfo[$s] = $v->$s;
                        $rule[] = $s;
                        $totalPrice += $v->$s * $v->one_price;
                        $totalCount += $v->$s;
                        $customSku = $customList[$key] ?? [];
                        if (empty($customSku)){
                            $error .= $key.'未找到对应custom_sku'."\n";
                            continue;
                        }
                        $updateSkuList[$v->contract_no][] = [
                            'spu'           => $v->spu,
                            'spu_id'        => $v->spu_id,
                            'custom_sku'    => $customSku->custom_sku,
                            'custom_sku_id' => $customSku->id,
                            'size'          => $s,
                            'num'           => $v->$s,
                            'price'         => $v->one_price,
                            'contract_no'   => $v->contract_no,
                            'color'         => $v->color_identifying,
                            'color_name'    => $v->color_name,
                            'name'          => $customSku->name,
                            'order_id'      => $v->order_id
                        ];
                    }
                }
                $update = db::table('cloudhouse_contract')
                    ->where('id', $v->id)
                    ->update([
                        'num_info' => json_encode($sizeInfo, true),
                        'rule' => implode(',', $rule),
                        'count' => $totalCount,
                        'price' => $totalPrice
                    ]);
                if (isset($totalList[$v->contract_no])){
                    $totalList[$v->contract_no]['total_count'] += $totalCount;
                    $totalList[$v->contract_no]['total_price'] += $totalPrice;
                }else{
                    $totalList[$v->contract_no] = [
                        'total_count' => $totalCount,
                        'total_price' => $totalPrice
                    ];
                }
            }

            foreach ($totalList as $contractNo => $v){
                db::table('cloudhouse_contract_total')
                    ->where('contract_no', $contractNo)
                    ->update([
                        'total_count' => $v['total_count'],
                        'total_price' => $v['total_price']
                    ]);
            }

            foreach ($updateSkuList as $contractNo => $list){
                db::table('cloudhouse_custom_sku')
                    ->where('contract_no', $contractNo)
                    ->delete();
                foreach ($list as $save){
                    $id = db::table('cloudhouse_custom_sku')
                        ->insertGetId($save);
                    if (empty($id)){
                        $error .= json_encode($save).'新增失败！'."\n";
                        continue;
                    }
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => $params['contract_no'].'更新成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => $e->getMessage().'；位置：'.$e->getLine()];
        }
    }
//    public function mytest()
//    {
//        try {
//            $contract = db::table('cloudhouse_contract')
//                ->get();
//            $list = [];
//            foreach ($contract as $v){
//                $list[$v->contract_no] = $v->create_user;
//            }
//            $contractMdl = db::table('cloudhouse_contract_total')
//                ->where('input_user_id', 0)
//                ->get();
//            db::beginTransaction();
//            foreach ($contractMdl as $v){
//                $userId = $list[$v->contract_no] ?? 0;
//                db::table('cloudhouse_contract_total')
//                    ->where('id', $v->id)
//                    ->update([
//                        'maker_id' => $userId,
//                        'input_user_id' => $userId
//                    ]);
//            }
//            db::commit();
//            return '更新成功！';
//        }catch (\Exception $e){
//            db::rollback();
//            return '更新失败！'.$e->getMessage();
//        }
//    }
    public function updateSpuCate()
    {
        try {
            $spuMdl = db::table('self_spu')
                ->where('type', 2)
                ->where('one_cate_id', 0)
                ->get();
            $groupSpuMdl = db::table('self_group_spu as a')
                ->leftJoin('self_spu as b', 'a.group_spu_id', '=', 'b.id')
                ->get(['b.one_cate_id', 'b.two_cate_id', 'b.three_cate_id', 'a.*']);
            $groupSpuList = [];
            foreach ($groupSpuMdl as $g){
                if (isset($groupSpuList[$g->spu_id])){
                    continue;
                }else{
                    $groupSpuList[$g->spu_id] = $g;
                }
            }

            db::begintransaction();
            foreach ($spuMdl as $v){
                $groupSpu = $groupSpuList[$v->id] ?? [];
                if (empty($groupSpu)){
                    continue;
                }
                $update = db::table('self_spu')
                    ->where('id', $v->id)
                    ->update([
                        'one_cate_id' => $groupSpu->one_cate_id,
                        'two_cate_id' => $groupSpu->two_cate_id,
                        'three_cate_id' => $groupSpu->three_cate_id,
                    ]);
                if (!$update){
                    throw new \Exception('spuId:'.$v->id.'修改失败！');
                }
            }
            db::commit();
            return ['code' => 200, 'msg' => '修改成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => $e->getMessage()];
        }

    }
}//
